package cn.iocoder.yudao.module.infra.controller.admin.base;

import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.exception.BusinessException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.web.core.util.BaseController;
import cn.iocoder.yudao.module.infra.api.base.dto.ColumnModel;
import cn.iocoder.yudao.module.infra.api.base.dto.QueryConditionDto;
import cn.iocoder.yudao.module.infra.dal.dataobject.base.DynamicTable;
import cn.iocoder.yudao.module.infra.service.base.DynamicTableService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/infra/base/dynamicTable")
public class DynamicTableController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(DynamicTableController.class);

    @Resource
    private DynamicTableService dynamicTableService;

    @GetMapping(value = "/getTable/{name}", produces = "application/json")
    public Map<String, Object> getTable(@PathVariable String name) {
        DynamicTable model = dynamicTableService.getDateModelBySqlName(name);
        if (model == null) {
            throw new BusinessException("不存在该数据类型");
        }
        List<ColumnModel> cols = JsonUtils.parseArray(model.getColsJson(), ColumnModel.class);
        List<QueryConditionDto> queryDtos = new ArrayList<>();
        Map<String, String> modelInstance = new HashMap<>();
        for (ColumnModel col : cols) {
            modelInstance.put(col.getColSqlName(), "");
            if (!"0".equalsIgnoreCase(col.getColQueryType())) {
                if ("3".equalsIgnoreCase(col.getColQueryType())) {
                    QueryConditionDto beginQueryDto = new QueryConditionDto();
                    beginQueryDto.setQueryName(col.getColSqlName() + " _MIN");
                    beginQueryDto.setQueryDescribe(col.getColName() + "  >=");
                    beginQueryDto.setQueryType("date");
                    queryDtos.add(beginQueryDto);
                    QueryConditionDto endQueryDto = new QueryConditionDto();
                    endQueryDto.setQueryName(col.getColSqlName() + " _MAX");
                    endQueryDto.setQueryDescribe(col.getColName() + "  <=");
                    endQueryDto.setQueryType("date");
                    queryDtos.add(endQueryDto);
                } else {
                    QueryConditionDto queryDto = new QueryConditionDto();
                    queryDto.setQueryType(col.getColDataType());
                    queryDto.setQueryName(col.getColSqlName());
                    queryDto.setQueryDescribe(col.getColName());
                    queryDto.setIsIndex(col.getColIsIndex());
                    queryDtos.add(queryDto);
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("dataModel", model);
        result.put("queryConditions", queryDtos);
        result.put("colModel", cols);
        result.put("modelInstance", modelInstance);
        return result;
    }

    @GetMapping(value = "/listTable", produces = "application/json")
    public List<DynamicTable> listTable() {
        return dynamicTableService.list();
    }

    @PostMapping(value = "/saveOrUpdateTable", produces = "application/json")
    public void saveOrUpdateTable(String modelJson) {
        if (StringUtils.isBlank(modelJson)) {
            throw new BusinessException("modelJson不能为空");
        }
        LOG.info("开始处理basedata数据 {}", modelJson);
        DynamicTable model = JsonUtils.parseObject(modelJson, DynamicTable.class);
        if (model == null || StringUtils.isBlank(model.getDataSqlName())) {
            throw new BusinessException("modelJson数据异常").addAttachment(modelJson);
        }
        model.setCreator(getLoginUserId().toString());
        dynamicTableService.saveNewDataModel(model);
    }

    @PostMapping(value = "/listTableData", produces = "application/json")
    public PageResult<Map<String, Object>> listTableData(String table, String queryData, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        DynamicTable dynamicTable = dynamicTableService.getDateModelBySqlName(table);
        if (dynamicTable == null) {
            throw new BusinessException("数据为空:" + table);
        }
        return dynamicTableService.getDataCols(dynamicTable, queryData, pageNum, pageSize);
    }

    @PostMapping(value = "/addTableData", produces = "application/json")
    public void addModelData(String newModelData, String dataSqlName) {
        dynamicTableService.addModelData(newModelData, dataSqlName, getLoginUserId().toString());
    }

    @PostMapping(value = "/deleteTableData", produces = "application/json")
    public String deleteModelData(String id, String dataSqlName) {
        int result = 0;
        if (StringUtils.isNotBlank(id)) {
            List<Integer> idList = new ArrayList<>();
            idList.add(Integer.valueOf(id));
            result = dynamicTableService.deleteModelData(idList, dataSqlName, getLoginUserId().toString());
        }
        return "成功删除" + result + "条记录";
    }

    @PostMapping(value = "/editTableData", produces = "application/json")
    public void editModelData(String newModelData, String dataSqlName) {
        dynamicTableService.editModelData(newModelData, dataSqlName, getLoginUserId().toString());
    }


    @PostMapping(value = "/listXCRUDData/{name}", produces = "application/json")
    public PageResult<Map<String, Object>> listXCRUDData(@PathVariable String name, @RequestBody JSONObject params) {
        return dynamicTableService.listXCRUDData(name, params);
    }

    @PostMapping(value = "/addXCRUDData/{name}", produces = "application/json")
    public void addCRUDData(@PathVariable String name, @RequestBody JSONObject params) {
        dynamicTableService.addXCRUDData(name, params, getLoginUserId().toString());
    }

    @PostMapping(value = "/updateXCRUDData/{name}", produces = "application/json")
    public void updateCRUDData(@PathVariable String name, @RequestBody JSONObject params) {
        dynamicTableService.updateXCRUDData(name, params, getLoginUserId().toString());
    }

    @PostMapping(value = "/delXCRUDData/{name}", produces = "application/json")
    public void delCRUDData(@PathVariable String name, Long id) {
        dynamicTableService.delXCRUDData(name, id, getLoginUserId().toString());
    }

    @GetMapping(value = "/getXCRUDData/{name}", produces = "application/json")
    public Map<String, Object> getCRUDData(@PathVariable String name, Long id) {
        return dynamicTableService.getXCRUDData(name, id, getLoginUserId().toString());
    }
}
